from typing import List
from app.sql.schema import DetectorCreate
from sqlalchemy.orm import Session
from app.sql import models


def add_detector(model: DetectorCreate, db: Session):
    obj = models.Detector(id=model.id, coord_x=model.coord_x, coord_y=model.coord_y)
    db.add(obj)
    db.commit
    for item in model.anomalies:
        obj = models.Anomaly(id=item.id, g=item.g, detector_id = item.detetctor_id)
        db.add(obj)
    db.commit()
    return 'ok'
def get_anomalies(db: Session):
    return anomalies_analizer(db.query(models.Anomaly).all())

def anomalies_analizer(data: List[models.Anomaly]):
    res = {}
    for anomaly in data:
        if anomaly.id not in res:
            res.update({anomaly.id:[]})
            res[anomaly.id].append({'x':anomaly.x_detector_coord,'y':anomaly.y_detector_coord,'g':anomaly.g})

        else:
            res[anomaly.id].append({'x':anomaly.x_detector_coord,'y':anomaly.y_detector_coord,'g':anomaly.g})
    return f(res)
def f(a):
    res={}
    for key in a:
        sxc = 0
        syc = 0
        msum=0
        dataset = a[key]
        for coords in dataset:
            sxc+=coords['x']*coords['g']
            syc+=coords['y']*coords['g']
            msum+=coords['g']
        res.update({key:{'x':sxc/msum,'y':syc/msum}})
    return res
